package com.stone.springboot.Test.aspect;

import com.stone.springboot.Test.exception.MyBizException;
import com.stone.springboot.Test.pojo.ResultBean;
import com.sun.xml.internal.ws.api.model.CheckedException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * Created by stone on 2017/8/25.
 */
@Component
@Aspect
@Slf4j
public final class ControllerAOP {

	@Pointcut(value = "execution(* com.stone.springboot.Test.controller..*.*(..))")
	private void pointCut(){}

	@Around(value = "com.stone.springboot.Test.aspect.ControllerAOP.pointCut()")
	public ResultBean<?> handlerControllerMethod(ProceedingJoinPoint pjp) {
		ResultBean<?> result;
		try {
			result = (ResultBean<?>) pjp.proceed();
		} catch (Throwable e) {
			result = this.handlerException(pjp, e);
		}
		log.info("返回值,{}",result);
		return result;
	}

	private ResultBean<?> handlerException(ProceedingJoinPoint pjp, Throwable e) {
		ResultBean<?> result = new ResultBean();
		if (e instanceof CheckedException) {
			return result.setMsg(e.getLocalizedMessage()).setCode(ResultBean.FAIL);
		}
		if(e instanceof MyBizException){
			final MyBizException myBizException = (MyBizException) e;
			return result.setMsg(myBizException.getMessage()).setCode(myBizException.getCode());
		}
		return result.setMsg(e.getMessage()).setCode(ResultBean.FAIL);
	}
}
